package com.xd.case3;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.retry.RetryForever;

public class CuratorLockTest {

    private static String connectString = "zookeeper1:2181,zookeeper2:2181,zookeeper3:2181";
    private static int connectionTimeout = 3000;
    private static int sessionTimeout = 200000;

    public static void main(String[] args) {
        //创建分布式锁1
        InterProcessLock lock1 = new InterProcessMutex(getCuratorFramwork(), "/locks");

        //创建分布式锁2
        InterProcessLock lock2 = new InterProcessMutex(getCuratorFramwork(), "/locks");

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 获取锁对象
                try {
                    lock1.acquire();
                    System.out.println("线程1获取锁");

                    lock1.acquire();
                    System.out.println("线程1再次获取到锁");
                    Thread.sleep(5 * 1000);

                    lock1.release();
                    System.out.println("线程1释放锁");
                    lock1.release();
                    System.out.println("线程1再次释放锁");
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 获取锁对象
                try {
                    lock2.acquire();
                    System.out.println("线程2获取锁");

                    lock2.acquire();
                    System.out.println("线程2再次获取到锁");
                    Thread.sleep(5 * 1000);

                    lock2.release();
                    System.out.println("线程2释放锁");
                    lock2.release();
                    System.out.println("线程2再次释放锁");
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    private static CuratorFramework getCuratorFramwork() {
        //重试策略，初试时间 3 秒，重试 3 次
        RetryPolicy policy = new ExponentialBackoffRetry(3000, 3);

        //通过工厂创建 Curator
        CuratorFramework client = CuratorFrameworkFactory.builder().connectString(connectString).connectionTimeoutMs(connectionTimeout)
                .sessionTimeoutMs(sessionTimeout).retryPolicy(policy).build();
        //开启连接
        client.start();

        System.out.println("zookeeper初始化完成");

        return client;
    }

}
